"use client";

import { signIn } from "next-auth/react";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card";

export default function LoginPage() {
  const router = useRouter();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    const res = await signIn("credentials", {
      username,
      password,
      redirect: false,
    });

    console.log(res);

    if (res?.error) {
      setError("登录失败，请检查账号密码");
    } else {
      // ✅ 获取 session 再跳转
      const sessionRes = await fetch("/api/auth/session");
      const session = await sessionRes.json();
      const role = session?.user?.role;
      const username = session?.user?.name;

      if (role === "admin") {
        router.push("/gpa/uploads");
      } else if (role === "student") {
        router.push(`/gpa/detail/${username}`);
      } else {
        router.push("/login"); // fallback
      }
    }
  };

  return (
    <div className="flex items-center justify-center min-h-[75vh]">
      <Card className="w-full shadow-lg p-6 border-gray-200 space-y-4 rounded-md min-w-[500px]">
        <CardHeader className="w-full text-center space-y-1 max-w-dvw justify-center">
          <p className="w-full text-md text-muted-foreground">
            武汉大学信息管理学院
          </p>
          <CardTitle className="w-full text-2xl font-semibold">
            绩点测算平台
          </CardTitle>
          <p className="w-full text-md text-muted-foreground">
            登录账号是学号，密码是身份证后6位，末尾位X一定要大写。
          </p>
        </CardHeader>
        <CardContent>
          {error && (
            <p className="text-red-500 text-sm text-center mb-4">{error}</p>
          )}
          <form onSubmit={handleLogin} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="username">账号</Label>
              <Input
                id="username"
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="请输入账号"
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">密码</Label>
              <Input
                id="password"
                type="password"
                value={password}
                placeholder="请输入密码"
                onChange={(e) => setPassword(e.target.value)}
                required
              />
            </div>
            <Button type="submit" className="w-full">
              登录
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
